<template>
	<view class="content">
		<view class="flex-r jsb">
			<view
				class="title fb textCenter"
				:class="{ on: index == isActive }"
				v-for="(item, index) in tab"
				@click="handletabClick(index)"
			>
				{{ item }}
			</view>
		</view>
		<template v-if="isActive == 0">
			<view class="mt16 fm">
				<input type="text" placeholder="输入手机号" v-model="form.userName" />
				<input type="password" placeholder="输入登录密码" v-model="form.userPassword" />
			</view>
			<view class="btn white textCenter" @tap="submit">用户注册</view>
		</template>
		<template v-else>
			<view class="mt16 fm">
				<input type="text" placeholder="输入手机号" v-model="adminForm.userName" />
				<input type="password" placeholder="输入登录密码" v-model="adminForm.userPassword" />
				<input type="text" placeholder="输入邀请码" v-model="adminForm.tInvitationcode" />
			</view>
			<picker @change="bindPickerChange" :range="deptList" range-key="label" :value="index">
				<view class="picker">{{ deptList[index] ? deptList[index].label : '请选择市场' }}</view>
			</picker>
			<view class="btn white textCenter" @tap="submitadmin">商户注册</view>
		</template>

		<view class="textCenter mt16">
			<text style="color: #999">已有账号？</text>
			<text style="color: #c40414" @tap="handleClick">立即登录</text>
		</view>
	</view>
</template>

<script>
import Utils from '@/utils/utils.js'
import { ykRegister, shRegister, getWxOpenid, wxOpenidLogin, getdeptList } from '@/api/login.js'
export default {
	data() {
		return {
			isActive: 0,
			tab: ['用户注册', '商户注册'],
			form: {
				userName: '',
				userPassword: '',
				tOpenid: ''
			},
			deptList: [],
			adminForm: {
				userName: '',
				userPassword: '',
				tInvitationcode: '', // 邀请码
				tDeptid: ''
			},
			// deptList: [
			// 	{ label: '市场1', value: '103' },
			// ],
			index: -1, // 初始化为 -1 表示没有选择
			submitFlag: true
		}
	},
	onLoad(option) {
		console.log(option)
		this.isActive = option.type
		// let openid = uni.getStorageSync('openid')
		// console.log('loading-->', openid)
		// if (openid) {
		// 	wxOpenidLogin(openid).then(
		// 		(res) => {
		// 			console.log(res)
		// 			if (res.token == undefined) {
		// 				Utils.toast('请先注册!')
		// 			} else {
		// 				Utils.saveToken(res.token)
		// 				uni.switchTab({
		// 					url: '/pages/mine/mine',
		// 					success: function () {
		// 						setTimeout(() => {
		// 							Utils.toast('登录成功!')
		// 						}, 300)
		// 					}
		// 				})
		// 			}
		// 		},
		// 		(err) => {
		// 			console.log(err)
		// 		}
		// 	)
		// }
		this.getdept()
	},
	methods: {
		bindPickerChange(e) {
			const selectedIndex = e.detail.value
			this.index = selectedIndex
			// 确认选择后，将对应的 value 赋值给 adminForm.tDeptid
			this.adminForm.tDeptid = this.deptList[selectedIndex].value
			console.log('用户选择了:', this.adminForm.tDeptid)
		},
		getdept() {
			getdeptList().then((res) => {
				console.log(res)
				const transformedArray = res.deptList.map((item) => ({
					label: item.deptName, // 将 deptName 作为 label
					value: item.deptId // 将 deptId 作为 value，并转换为字符串（如果需要）
				}))
				this.deptList = transformedArray
			})
		},
		handletabClick(index) {
			this.isActive = index
		},
		getCode() {
			let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/ // 手机号的正则表达式
			if (!reg.test(this.form.tel)) {
				// 判断手机号格式是否正确
				Utils.toast('手机号格式不正确')
			} else {
				getSmCode(this.form.tel).then(
					(res) => {
						Utils.toast(res.code)
					},
					(err) => {
						console.log(err)
					}
				)
			}
		},
		async submit() {
			const resA = await this.getOpenid()
		},
		async submitadmin() {
			const resA = await this.getadmin()
		},
		getOpenid() {
			const regex = /^[1][3-9][0-9]{9}$/
			if (!regex.test(this.form.userName)) return Utils.toast('请输入正确的手机号')
			//if (this.form.userName == '') return Utils.toast('用户名不能为空')
			if (this.form.userPassword == '') return Utils.toast('密码不能为空')
			return new Promise((resolve, reject) => {
				// 获取jscode
				uni.login({
					provider: 'weixin',
					success: async (res) => {
						console.log('res-login', res)
						uni.showLoading({
							mask: true,
							title: '注册中，请稍后...'
						})
						if (res.errMsg == 'login:ok') {
							//拿到code调后台
							console.log('code=>', res.code)
							getWxOpenid(res.code).then(
								(res) => {
									if (res.code == 200) {
										console.log('openid???=>', res.result.openid)
										uni.setStorageSync('openid', res.result.openid)
										let openId = res.result.openid
										let params = {
											userName: `hy_${this.form.userName}`,
											tPhone: this.form.userName,
											userPassword: this.form.userPassword,
											tOpenid: openId
										}
										if (this.submitFlag) {
											//游客注册
											ykRegister(params).then(
												(res) => {
													console.log(res)
													Utils.toast(res.msg)
													if (res.code == 200) {
														console.log('注册成功')
														this.submitFlag = false
														uni.hideLoading()

														wxOpenidLogin(openId).then(
															(res) => {
																console.log(res)
																if (res.code == 200) {
																	uni.setStorageSync('loginState', 1)
																	Utils.saveToken(res.token)
																	uni.switchTab({
																		url: '/pages/mine/mine',
																		success: function () {
																			setTimeout(() => {
																				Utils.toast('登录成功!')
																			}, 300)
																		}
																	})
																}
															},
															(err) => {
																console.log(err)
															}
														)
													}
												},
												(err) => {
													console.log(err)
												}
											)
										}
									}
								},
								(err) => {
									console.log(err)
								}
							)
						}
					}
				})
			})
		},

		getadmin() {
			const regex = /^[1][3-9][0-9]{9}$/
			if (!regex.test(this.adminForm.userName)) return Utils.toast('请输入正确的手机号')
			// if (this.adminForm.userName == '') return Utils.toast('用户名不能为空')
			if (this.adminForm.userPassword == '') return Utils.toast('密码不能为空')
			if (this.adminForm.tDeptid == '') return Utils.toast('请选择市场')
			let params = {
				userName: `sh_${this.adminForm.userName}`,
				tPhone: this.adminForm.userName,
				userPassword: this.adminForm.userPassword,
				tDeptid: this.adminForm.tDeptid,
				tInvitationcode: this.adminForm.tInvitationcode
			}
			console.log(params)
			shRegister(params).then(
				(res) => {
					console.log(res)
					if (res.code == 200) {
						uni.navigateTo({
							url: `/pages_B/login/login?type=${this.isActive}`,
							success: function () {
								setTimeout(() => {
									Utils.toast(res.msg)
								}, 300)
							}
						})
					} else {
						uni.$u.toast(res.msg)
					}
				},
				(err) => {
					console.log(err)
				}
			)
		},
		handleClick() {
			uni.navigateTo({
				url: `/pages_B/login/login?type=${this.isActive}`
			})
		}
	}
}
</script>

<style lang="stylus" scoped>
.relative
	position relative
.content
	min-height 100%
	padding 80rpx
.title
	width 150rpx
	line-height 80rpx
.on
	border-bottom 4rpx solid #c40414
.fm input
	border none
	height 120rpx
	line-height 120rpx
	border-bottom 1rpx solid #ccc
.btn
	margin-top 60rpx
	line-height 100rpx
	height 100rpx
	border-radius 50rpx
	background #c40414
.picker
	height 120rpx
	line-height 120rpx
	color: #666
	border-bottom: 1rpx solid #ccc
	border-radius: 10rpx
</style>
